package cn.xiqi.cms.hibernate.DAO;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.xiqi.cms.hibernate.beans.Loginfo;

public class LogDAOImpl implements LogDAO{

	@Override
	public int insert(Loginfo record) {
		Session session = null;
		Transaction tx = null;
		int id = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.save(record);
			id = record.getLogID();
			tx.commit();
		}
		catch (HibernateException e){
			throw e;
		}
		finally {
			if(tx!=null){
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return id;
	}

	@Override
	public boolean delete(Loginfo record) {
		Session session = null;
		Transaction tx = null;
		boolean b = true;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.delete(record);
			tx.commit();
		}
		catch (HibernateException e) {
			b = false;
			throw e;
		}
		finally {
			if(tx!=null) {
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return b;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Loginfo> select(Map<String, Object> values) {
		Session session = null;
		List<Loginfo> records = null;
		Query query = null;
		String type;
		int page = 0;
		int size = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			type = (String)values.get("type");
			if(type.equals("id")){
				query = session.createQuery("from Loginfo where logID=?");
				query.setInteger(0, (Integer)values.get("id"));
			}else if(type.equals("all")) {
				query = session.createQuery("from Loginfo");
			}else if(type.equals("type")) {
				query = session.createQuery("from Loginfo where type=?");
				query.setInteger(0, (Integer)values.get("typeid"));
			}else if(type.equals("user")) {
				query = session.createQuery("from Loginfo where usrID=?");
				query.setInteger(0, (Integer)values.get("user"));
			}else if(type.equals("time")) {
				query = session.createQuery("from Loginfo where logtime > ? and logtime < ?");
				Date start = (Date)values.get("start");
				Date end = (Date)values.get("end");
//				query.setDate(0, start);
//				query.setDate(1, end);
				query.setParameter(0, start);
				query.setParameter(1, end);
			}
			if(values.containsKey("page")&& values.containsKey("size")){
				page = (int)values.get("page");
				size = (int)values.get("size");
				query.setFirstResult((page - 1) * size);
				query.setMaxResults(size);
			}
		}catch (Exception e) {
			throw e;
		} finally {
			records = query.list();
			query = null;
			HibernateSessionFactory.closeSession();
		}
		return records;
	}
	
}
